<template>
  <v-layout type="main">
    <!-- <p class="page-title" v-if="notebook_flag">模型开发</p> -->
    <!-- <p class="page-title" v-if="!notebook_flag">我的任务</p> -->
    <!-- <div class="detail-box" v-if="detailData">
      <div class="pic">
        <v-image class="avatar" :src="detailData.avatar" alt="" />
      </div>
      <div class="word">
        <h3 class="title">
          {{detailData.alias}} // 注释掉
          <h3 class="info-title"> {{ detailData.name }}<i class="el-icon-edit-outline alick-btn-edit"
              @click="updateBase" /></h3>
          <el-button class="back" type="text" icon="el-icon-right" @click="$router.push({ path: '/notebook' })" />
        </h3>
        <p class="hint">
          <span>状态：<strong :class="['alick-layout-status', detailData.status]">{{
            statusMap[detailData.status]
          }}</strong></span> {{ detailData.desc }}
        </p>

        <div class="alick-handle-btns">
          <a class="handle-btn" href="javascript:;" @click="start" v-show="detailData.status == 'terminated'">启动</a>
          <a class="handle-btn" href="javascript:;" @click="stop" v-show="detailData.status != 'terminated'">停止</a>
          <a class="handle-btn" href="javascript:;" @click="entry" v-show="detailData.status == 'running'">进入</a>
          <el-popover placement="bottom-end" width="80" trigger="hover">
            <div class="alick-popover-handle-btns">
              <a class="handle-btn" href="javascript:;" @click="exportModel">导出模型</a>
              <a class="handle-btn" href="javascript:;" @click="exportTask">训练任务</a>
              <a class="handle-btn" href="javascript:;" @click="exportMarketAlgorithm">发布到AI市场</a>
            </div>
            <a class="handle-btn" href="javascript:;" slot="reference">更多</a>
          </el-popover>
        </div>
      </div>
    </div> -->

    <div class="layout-top">
      <div class="rollback" @click="$router.push('/notebook')">
        <img src="~@/assets/img/prev.png" alt="">
        <span>返回</span>
      </div>

      <div class="code-description">
        <div class="dea_top">
          <div>
            <el-image class="nav_box" :src="detailData.avatar ? detailData.avatar : require('@/assets/img/drone3.jpg')"
              fit="fit"></el-image>
          </div>

          <div class="header_box">
            <div class="code-desc-header">
              <div class="title">
                <div class="title-header">
                  <span>{{ detailData.name }}</span>
                </div>

                <div class="code-tags">
                  <div class="user-tag tag">
                    <img src="~@/assets/img/user.png" alt="">
                    {{
                      detailData.create_user && (detailData.create_user.nick_name ||
                        detailData.create_user.username)
                    }}
                  </div>

                  <div :class="['status-tag tag', {
                        'danger': detailData.status === 'terminated',
                        'warning': detailData.status != 'terminated' && detailData.status != 'running',
                        'success': detailData.status === 'running'
                      }]">
                    {{ statusMap[detailData.status] }}
                  </div>

                  <div class="time-tag tag">
                    <span>创建时间：</span>
                    {{ detailData.create_time }}
                  </div>

                  <div class="time-tag tag">
                    <span>更新时间：</span>
                    {{ detailData.update_time }}
                  </div>
                </div>

                <div class="staet_box">
                  <plug-state :statusStr="detailData.status" />
                </div>
              </div>
              <!-- <div class="code-status">
              <plug-state :statusStr="detailData.status" />
            </div> -->
            </div>
          </div>
        </div>

        <!-- <div class="desc-container">
        <el-input type="textarea" placeholder="暂无描述信息" :autosize="{ minRows: 4, maxRows: 4 }" disabled
          v-model="detailData.desc" style="cursor: pointer" />
      </div> -->
      </div>


      <div class="btns-container">
        <div class="alick-handle-btns">
          <!-- <a class="handle-btn" href="javascript:;" @click="start" v-show="detailData.status == 'terminated'">启动</a>
          <a class="handle-btn" href="javascript:;" @click="stop" v-show="detailData.status != 'terminated'">停止</a>
          <a class="handle-btn" href="javascript:;" @click="entry" v-show="detailData.status == 'running'">进入</a> -->

          <el-button class="handle-btn" type="primary" size="medium" @click="entryTensorboard"
            v-show="detailData.status == 'running' && detailData.tensorboard">
            打开tensorboard
          </el-button>
          <el-button class="handle-btn" type="primary" size="medium" @click="entry"
            v-show="detailData.status == 'running'">
            进入
          </el-button>

          <el-button class="handle-btn" type="success" size="medium" @click="start"
            v-show="detailData.status == 'terminated'">
            启动
          </el-button>
          <el-button class="handle-btn" type="danger" size="medium" @click="stop"
            v-show="detailData.status != 'terminated'">
            停止
          </el-button>

          <el-popover placement="bottom-end" width="80" trigger="hover">
            <div class="alick-popover-handle-btns">
              <a class="handle-btn" href="javascript:;" @click="exportModel">导出模型</a>
              <a class="handle-btn" href="javascript:;" @click="exportTask">训练任务</a>
              <a class="handle-btn" href="javascript:;" @click="exportMarketAlgorithm">发布到公开算法</a>
            </div>
            <!-- <a class="handle-btn" href="javascript:;" slot="reference">更多</a> -->
            <el-button class="handle-btn" type="warning" size="medium" slot="reference">更多</el-button>
          </el-popover>
        </div>
      </div>
    </div>

    <!-- <div class="code-status">
      <plug-state :statusStr="detailData.status" />
    </div> -->

    <!-- <ul class="nav-alike" v-show="!$route.meta.hideDetails">
      <li v-for="(e, i) in thisRouter" :class="{ 'active': e.name == $route.name }" @click="skip(e)" :key="i">
        {{ e.meta.title }}
        <span class="nav-alike-item">{{ e.meta.title }}</span>
      </li>
    </ul> -->
    <!-- <el-radio-group v-model="nowRouter" size="medium" @change="skip" class="nav-alike" v-show="!$route.meta.hideDetails">
      <el-radio-button :label="e.name" v-for="(e, i) in thisRouter" :key="i">
        <span class="nav-alike-item">{{ e.meta.title }}</span>
      </el-radio-button>
    </el-radio-group> -->

    <!--    <el-tabs v-model="nowRouter" @tab-click="skip">-->
    <!--      <el-tab-pane :label="e.meta.title" :name="e.name" v-for="(e, i) in thisRouter" :key="i"/>-->
    <!--    </el-tabs>-->

    <!-- <div class="radio_box">
      <el-radio-group v-model="nowRouter" v-show="!$route.meta.hideDetails" @input="skip">
        <el-radio-button :label="e.name" :name="`${e.name}`" v-for="(e, i) in thisRouter" :key="i">
          {{ e.meta.title }}
        </el-radio-button>
      </el-radio-group>
    </div> -->

    <div class="tabs-left">
      <el-tabs v-model="nowRouter" @tab-click="skip" v-show="!$route.meta.hideDetails">
        <el-tab-pane :label="e.meta.title" :name="e.name" v-for="(e, i) in thisRouter" :key="i" />
      </el-tabs>
    </div>

    <div :class="['layout-content', { 'layout-content-nodetail': $route.meta.hideDetails }]">
      <router-view class="content-detail" :detailData.sync="detailData" v-if="detailData" @getDetail="getDetail" />
    </div>

    <el-dialog :visible.sync="showUpdateBaseDialog" title="模型开发基本信息" width="840px">
      <el-form class="form myself-form" ref="form" :rules="baseSubmitRules" :model="addForm" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="配图">
          <media-uploader accept=".jpg,.jpeg,.png,.JPG,.JPEG" :src="addForm.avatar" @avatarPath="avatarPath" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :rows="3" v-model="addForm.desc" />
        </el-form-item>
        <el-form-item label=" ">
          <el-button class="none-type" type="primary" @click="commitBase">确定</el-button>
          <el-button class="none-type" @click="cancelBase">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <div v-if="showExportModelDialog">
      <plug-export-model :show_file=showExportModelDialog @infoShow="infoShowExport" :model_id=model_id
        :biz_id=detailData.id :business_type="1" />
    </div>
  </v-layout>
</template>

<script>
import { getMarketAlgorithmBySource } from "@/api/marketAlgorithm"
import { getAllTasks } from "@/api/task"
import { getModelBySource } from "@/api/model"
import { getExperimentDetail, putExperiment, startExperiment, stopExperiment, createPvc, deletePvc } from '@/api/notebook'
import { domain } from '@/config'
import { paramMap } from '@/utils/maps'
import plugExportModel from '@/components/module/plug-export-model'
import plugState from '@/components/module/plug-state'

export default {
  data() {
    return {
      notebook_flag: paramMap['notebook_flag'],
      thisRouter: [],
      nowRouter: this.$route.name,
      detailData: null,
      taskForm: {},
      addForm: {},
      modelForm: { visibility: 0 },
      marketForm: {},
      taskSubmitRules: {
        task_id: [
          { required: true, message: "该项为必填项" },
        ]
      },
      modelSubmitRules: {
        model_id: [
          { required: true, message: "该项为必填项" },
        ]
      },
      marketSubmitRules: {
        model_id: [
          { required: true, message: "该项为必填项" },
        ]
      },
      baseSubmitRules: {
        name: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
        ],
        desc: [
          { required: true, message: "该项为必填项" },
          { required: true, min: 1, max: 200, message: "长度在1到40个字符" },
        ],
      },
      showTaskDialog: false,
      showMarketDialog: false,
      showUpdateBaseDialog: false,
      showExportModelDialog: false,
      taskOptions: [],
      marketAlgorithmOptions: [],
      task: null,
      algorithm: null,
      model_id: null,
    };
  },
  components: {
    plugExportModel,
    plugState,
  },
  methods: {
    skip() {
      let path = `/notebook/${this.thisRouter.filter(e => e.name == this.nowRouter)[0].path}`
      if (path == this.$route.path) return
      this.$router.push({
        path,
        query: {
          id: this.$route.query.id
        }
      })
    },
    async getDetail() {
      if (!this.$route.query.id) return
      let res = await getExperimentDetail({ id: this.$route.query.id });
      if (res && res.data) {
        this.detailData = res.data;
        //console.log("detailData222222", this.detailData)
        this.addForm = JSON.parse(JSON.stringify(this.detailData))
      }
    },
    avatarPath(data) {
      this.addForm.avatar = data;
    },
    updateBase() {
      this.showUpdateBaseDialog = true
    },

    commitBase() {
      console.log(this.$refs, "addFormaddForm");
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let res = await putExperiment(this.addForm);
          if (res && res.data) {
            this.getDetail()
            this.showUpdateBaseDialog = false
          }
        }
      })
    },
    cancelBase() {
      this.showUpdateBaseDialog = false
    },
    async exportTask() {
      if (!this.$route.query.id) return
      let data = {
        source: this.detailData.id
      }
      let res = await getAllTasks(data);
      if (res && res.data) {
        let task_id
        if (res.data.length > 0) {
          task_id = res.data[0].id
        }
        let query = {
          experiment_id: this.detailData.id,
          task_id: task_id
        }
        this.$router.push({
          path: '/task/detail',
          query
        })
      }
      console.log('data', res.data)
      //this.showTaskDialog = true
    },
    async exportModel() {
      if (!this.$route.query.id) return
      let data = {
        source: this.detailData.id
      }
      let res = await getModelBySource(data);
      if (res && res.data) {
        this.model_id = res.data.id
      }
      this.showExportModelDialog = true
      console.log("showExportModelDialog", this.showExportModelDialog)
    },
    async exportMarketAlgorithm() {
      if (!this.$route.query.id) return
      let data = {
        source: this.detailData.id
      }
      let res = await getMarketAlgorithmBySource(data);
      let algorithm_id = null
      console.log("res", res)
      if (res && res.data) {
        if (res.data.length > 0) {
          algorithm_id = res.data.id
        }
      }
      console.log("res2", res)
      let query = {
        experiment_id: this.detailData.id,
        algorithm_id: algorithm_id
      }
      console.log("query", query)
      this.$router.push({
        path: '/market/algorithmdetail',
        query
      })
    },

    update() {
      let query = {
        id: this.detailData.id
      }
      this.$router.push({
        path: '/notebook/detail',
        query
      })
    },

    async start() {
      try {
        var res = await createPvc({ id: this.detailData.id })
        console.log("res:", res)
        var res1 = await startExperiment({ id: this.detailData.id });
        console.log("res1:", res1)
        /*              if (res1.code != 200){
                          await deletePvc({ id: this.detailData.id })
                      }*/
      } catch (e) {
        console.log("e:", e)
        await deletePvc({ id: this.detailData.id })
      }
    },
    async stop() {
      await stopExperiment({ id: this.detailData.id });
      console.log("stop")
      this.getDetail()
    },
    entry() {
      console.log(domain.split(':')[1])
      let path = `${domain.split(':')[1]}:32658` + this.detailData.experiment_url
      console.log('path', path)
      window.open(path, '_blank');
    },
    entryTensorboard() {
      console.log(domain.split(':')[1])
      let path = `${domain.split(':')[1]}:32658` + this.detailData.tensorboard_url
      console.log('path', path)
      window.open(path, '_blank');
    },
    refresh() {
      this.$EventBus.$on('experiment', e => {
        console.log(e)
        this.getDetail()
      })
    },
    infoShowExport(data) {
      this.showExportModelDialog = data
    }
  },
  mounted() {
    let temp = this.$router.options.routes.filter(
      e => e.name == 'notebook' && e.children
    )
    this.thisRouter = temp[0].children.filter(e => !e.meta.hideDetails)
    this.getDetail()
    this.refresh()

  },
  destroyed() {
    this.$EventBus.$off('experiment')
  },
}
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-layout.less";

.desc-container {
  margin-top: 20px;
}
</style>
